<?php
namespace app\system\controller;
use app\common\model\AccountLog;

class User extends Base {
    /*
     *@Notes 用户列表
    * @auth Milo-wang
    */
    public function index() {
        if(request()->isPost()){
            $key = input('post.key');
            $pageSize = input('limit/d');
            $order = input('order','id desc');
            $where = [];
            if($key) $where['nickname|phone'] = ['like','%'.$key.'%'];
            $list = model('user')->where($where)->order($order)->paginate($pageSize)->toArray();
            foreach($list['data'] as &$v) {
               $v['avatar'] = '<img onclick="previewImg(this)" src="'.$v['avatar'].'" style="height:300px" />';
               if($v['sex'] == 1){
                    $v['sex'] = '男';
                }elseif($v['sex'] == 2){
                    $v['sex'] = '女';
                }else{
                    $v['sex'] = '保密';
                }
                $v['levelList'] = model('user_level')->where('status=1')->field('id,grade')->select();
            }
            return ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        return $this->fetch();
    }

    /**
     * @Notes 用户添加
     */
    public function add() {
        if(request()->isPost()) {
            $data = input('post.');
            if(empty($data['avatar'])) $data['avatar'] = '/static/admin/images/avatar.png'; // 初始头像
            $data['create_time'] = time();
            // 增加客户
            $res = model('user')->insertGetId($data);
            if($res) return ajaxArray(1,'新增用户ID-'.$res. '成功');
            return ajaxArray(0,'新增失败');
        }
        return $this->fetch();
    }

    /**
     * @Notes 用户编辑
     */
    public function edit() {
        $id = input('id/d',0);
        if(request()->isPost()) {
           $data = input('post.','');
           // 数据重装
           $save  = [
                'avatar' => $data['avatar'],
                'phone' => $data['phone'],
                'nickname' => $data['nickname'],
                'sex' => $data['sex'],
                'status' => $data['status'],
                'update_time' => time()
           ];
           $res = model('user')->where('id',$id)->update($save);
           if($res) return ajaxArray(1,'编辑用户ID-'. $id .'成功');
           return ajaxArray(0,'编辑失败');
        }
        $user = model('user')->where('id',$id)->find();
        $this->assign('user',$user);           
        return $this->fetch();
    }

    /**
     * @Notes 用户状态
    */
    public function state() {
        $id = input('post.id/d',0);
        $status = model('user')->where('id',$id)->value('status');
        $status = $status ? 0 : 1;
        $result = model('user')->where('id',$id)->setField('status', $status);
        if ($result !== false) {
            return ajaxArray(1,'编辑成功',$status);
        }
        return ajaxArray(0,'编辑失败');
    }

    /**
     * @Notes table 编辑更新
     */
    public function update() {
        if(request()->isPost()) {
            $data = input('post.');
            $res = model('user')->where('id','eq', $data['id'])->update([$data['field'] => $data['value']]);
            if($res) {
                return ajaxArray(1,'修改成功');
            }
            return ajaxArray(0,'请重新编辑');
        }
    }
    /**
     * @Notes 用户等级
     */
    public function level() {
        if(request()->isPost()) {
            $pageSize = input('limit/d');
            $key = input('key','');
            $where = [];
            if($key) $where['grade'] = ['like','%'.$key.'%'];
            $data = model('user_level')->where($where)->paginate($pageSize)->toArray();
            foreach ($data['data'] as &$v){
                $v['image'] = '<img onclick="previewImg(this)" src="'.$v['image'].'" style="height:30px" />';
            }

            return ['code'=>0,'msg'=>'获取成功!','data'=>$data['data'],'count'=>$data['total'],'rel'=>1];
        }
        return $this->fetch();
    }
    
    /**
     * @Notes 用户等级添加
     */
    public function level_add() {
        if(request()->isPost()) {
            $data = input('post.');
            $save = [
                'grade' => $data['grade'],
                'price' => $data['price'],
                'image' => $data['image'],
                'mark' => $data['mark'],
                'status' => $data['status'],
                'add_time' => time()
            ];
            $res = model('user_level')->save($save);
            if($res) {
                return ajaxArray(1,'保存成功');
            }else {
                return ajaxArray(0,'保存失败，请重新保存');
            }
        }
        return $this->fetch();
    }
    /*
     *@Note 会员等级编辑
    */
    public function level_edit() {
        if(request()->isPost()) {
            $data = input('post.');
            $save = [
                'grade' => $data['grade'],
                'price' => $data['price'],
                'image' => $data['image'],
                'mark' => $data['mark'],
                'status' => $data['status']
            ];
            $res = model('user_level')->where(['id' => $data['id']])->update($save);
            if($res) {
                return ajaxArray(1,'保存成功');
            }else {
                return ajaxArray(0,'保存失败，请重新保存');
            }
        }
        $id = input('id');
        $level = model('user_level')->where(['id' => $id])->find();
        $this->assign('level',$level);
        return $this->fetch();
    }
    /**
     * @Notes 用户等级状态
    */
    public function level_state() {
        $id = input('post.id/d',0);
        $status = model('user_level')->where('id',$id)->value('status');
        $status = $status ? 0 : 1;
        $result = model('user_level')->where('id',$id)->setField('status', $status);
        if ($result !== false) {
            return ajaxArray(1,'编辑成功',$status);
        }
        return ajaxArray(0,'编辑失败');
    }

    /** 工具 */
    // 用户积分或余额的修改
    public function set_money_intergral() {
        $id = input('id/d',0);
        if(request()->isPost()) {
            $data = input('post.');
            $user = model('user')->where('id',$id)->find();
            if(empty($user)) return ajaxArray(0,'用户数据源错误');
            $account = new AccountLog(); 
            $res = $res_1 = $res_2 = $res_3 = true;
            if($data['money_type'] == 1 && $data['money'] != 0) { // 余额增加
               $money = floatval($user['money']) + floatval($data['money']);
               $res = model('user')->where('id',$id)->update(['money' => $money]);
               if($res) $account->changeAccountLog($id,$user['money'],0,$money,'money','系统增加用户余额'.$data['money'],1);
            }else if($data['money_type'] == 2 && $data['money'] != 0) { // 余额减少
                $money = floatval($user['money']) - floatval($data['money']);
               if($money < 0) return ajaxArray(0,'当前用户余额已不足最低值￥0');
               $res_1 = model('user')->where('id',$id)->update(['money' => $money]);
               if($res_1) $account->changeAccountLog($id,$user['money'],0,$money,'money','系统减少用户余额'.$data['money'],0);
            }
            if($data['intergral_type'] == 1 && $data['score'] != 0) { // 积分增加
                $score = floatval($user['score']) + floatval($data['score']);
                $res_2 = model('user')->where('id',$id)->update(['score' => $score]);
                if($res_2) $account->changeAccountLog($id,$user['score'],0,$score,'integral','系统增加用户积分'.$data['score'],1);
             }else if($data['intergral_type'] == 2 && $data['score'] != 0) { // 积分减少
                $score = floatval($user['score']) - floatval($data['score']);
                if($score < 0) return ajaxArray(0,'当前用户积分已不足最低值￥0');
                $res_3 = model('user')->where('id',$id)->update(['score' => $score]);
                if($res_3) $account->changeAccountLog($id,$user['score'],0,$score,'integral','系统减少用户积分'.$data['score'],0);
             }
            if($res && $res_1 && $res_2 && $res_3) return ajaxArray(1,'设置成功');
            return ajaxArray(0,'设置错误，请重新确认用户账户额度！');
        }
          
        return $this->fetch();
    }
}